package com.devunion.bogdan.spring;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>Class find all properties files in WEB-INF/classes directory.</p>
 *
 * @author: Andrey Tikhomirov
 */
public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    /**
     * Set location for all founded resources.
     *
     * @param locations Array of resources.
     */
    public void setLocations(Resource[] locations) {
        List<Resource> resources = new ArrayList<Resource>();

        for (Resource location : locations) {
            if (location.getFilename().contains("*")) {
                File[] files;
                try {
                    files = FileUtil.fileFilter(location.createRelative("").getFile()
                                .listFiles(), location.getFilename());
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }

                for (File file : files) {
                    resources.add(new ClassPathResource(file.getName()));
                }
            } else {
                resources.add(location);
            }
        }

        super.setLocations(resources.toArray(new ClassPathResource[resources.size()]));
    }
}
